package com.wsx.boots.auth.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created by wangshuaixin on 17/4/23.
 */
public class StatelessAuthorizingRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof StatelessAuthenticationToken;
    }

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String name = (String) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //模拟admin的登录才有role的权限
        if ("admin".equals(name)) {
            info.addRole("admin");
        }
        return info;
    }

    /**
     * 身份验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        StatelessAuthenticationToken statelessToken = (StatelessAuthenticationToken) token;
        String name = (String) statelessToken.getPrincipal();

        //获得秘钥，和客户端一样
        String key = getKey(name);

        //生成消息摘要
        String serverDigest = HmacSHA256Utils.digest(key, statelessToken.getParams());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(name, serverDigest, getName());
        return info;
    }

    /**
     * 获得秘钥，
     * @param name
     * @return
     */
    private String getKey(String name) {
        return "123edc";
    }
}
